import {Box, List} from "@mui/material";
import React, {useEffect, useState} from "react";
import {fetchPrice} from "../../moex/fetch-price";
import {PortfileAsset} from "../../investor/investor";
import data from "../../data/imoex.json";
import {Asset} from "../Asset/Asset";

interface AssetsListProps {
    assets: PortfileAsset[]
}

export const AssetsList = (props: AssetsListProps) => {
  const { assets } = props
  const [emptyMessage, setEmptyMessage] = useState<string>('Нет доступных активов')

  const getMinimalCapitalMessage = (firstAssetCode: string) => {
    fetchPrice(firstAssetCode)
      .then((price: number | null) => {
        if (price) setEmptyMessage(`Минимальная сумма ${price} руб.`)
      })
      .catch(err => console.log(err))
  }

  useEffect(() => {
    getMinimalCapitalMessage(data[0].code)
  }, [])

  return !assets.length
    ? <Box display="flex" justifyContent="center" alignItems="center" height="100px">
      {emptyMessage}
    </Box>
    : <List>
      {assets?.map((asset, i) =>
        <Asset key={`asset-${i}`} code={asset.code} price={asset.price} count={asset.count}/>)
      }
    </List>
}